package design.mode.dispatcher.util.excel;

import design.mode.dispatcher.util.bean.ExcelBean;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.util.*;

/**
 * easyexcel根据列重复数据动态合并单元格
 */
public class ExcelUtil3 {
    public static void main(String[] args) {
        String[] content = new String[]{"KPI类型", "KPI类型"};
        String fileName = "D:/" + "report" + System.currentTimeMillis() + ".xlsx";
        String title = "report" + System.currentTimeMillis();
        try{
            Workbook workbook = exportToExcel(content, title);
            FileOutputStream outputStream = new FileOutputStream(fileName);
            workbook.write(outputStream);
            outputStream.flush();
            workbook.close();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static Workbook exportToExcel(String[] content, String title) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(title);
        CellStyle cellStyle = workbook.createCellStyle();
        //水平对齐方式
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        // 设置水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setWrapText(true);

        Row firstRow = sheet.createRow(0);
        for (int i = 0; i < content.length; i++) {
            sheet.setColumnWidth(i, 30 * 256);
            Cell contentCell = firstRow.createCell(i);
            contentCell.setCellStyle(cellStyle);
            contentCell.setCellValue(content[i]);
        }


        List<ExcelBean> list = ExcelBean.getList();
        for (int i = 0; i < 17; i++) {
            Row contentRow = sheet.createRow(1 + i);
            for (int j = 0; j < 2; j++) {
                if (j == 0) {
                    Cell contentCell = contentRow.createCell(j);
                    contentCell.setCellStyle(cellStyle);
                    contentCell.setCellValue(list.get(i).getKpiType());
                } else {
                    Cell contentCell = contentRow.createCell(j);
                    contentCell.setCellStyle(cellStyle);
                    contentCell.setCellValue(list.get(i).getKpiTypeDetail());
                }
            }
        }

        return workbook;
    }

}
